package com.njym.quartz;

import com.njym.quartz.job.ReconciliationsJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 启动Quartz
 *
 * @author lianghui
 */
@Component
public class QuartzLaunchService {
    private static Logger logger = LoggerFactory.getLogger(QuartzLaunchService.class);

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    /**
     * 获取Job信息
     *
     * @param name
     * @param group
     * @return
     * @throws SchedulerException
     */
    public String getJobInfo(String name, String group) throws SchedulerException {
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger)scheduler.getTrigger(triggerKey);
        return String.format("time:%s,state:%s", cronTrigger.getCronExpression(), scheduler.getTriggerState(triggerKey).name());
    }

    /**
     * 修改某个任务的执行时间
     *
     * @param name
     * @param group
     * @param time
     * @return
     * @throws SchedulerException
     */
    public boolean modifyJob(String name, String group, String time) throws SchedulerException {
        Date date = null;
        TriggerKey triggerKey = new TriggerKey(name, group);
        CronTrigger cronTrigger = (CronTrigger)scheduler.getTrigger(triggerKey);
        String oldTime = cronTrigger.getCronExpression();
        if (!oldTime.equalsIgnoreCase(time)) {
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(time);
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(name, group).withSchedule(cronScheduleBuilder).build();
            date = scheduler.rescheduleJob(triggerKey, trigger);
        }
        return date != null;
    }

    /**
     * 暂停所有任务
     *
     * @throws SchedulerException
     */
    public void pauseAllJob() throws SchedulerException {
        scheduler.pauseAll();
    }

    /**
     * 暂停某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void pauseJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.pauseJob(jobKey);
    }

    /**
     * 恢复所有任务
     *
     * @throws SchedulerException
     */
    public void resumeAllJob() throws SchedulerException {
        scheduler.resumeAll();
    }

    /**
     * 恢复某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void resumeJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.resumeJob(jobKey);
    }

    /**
     * 删除某个任务
     *
     * @param name
     * @param group
     * @throws SchedulerException
     */
    public void deleteJob(String name, String group) throws SchedulerException {
        JobKey jobKey = new JobKey(name, group);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            return;
        }
        scheduler.deleteJob(jobKey);
    }

    @PostConstruct
    public void init() {
        logger.info("加载定时任务开始");
        try {
            //Scheduler scheduler = schedulerBean.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey("quartz-reconciliations", Scheduler.DEFAULT_GROUP);
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 30 10 * * ?");
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            JobDetail jobDetail = JobBuilder.newJob(ReconciliationsJob.class).withDescription("对账定时器").withIdentity("reconciliations-job", Scheduler.DEFAULT_GROUP).build();
            jobDetail.getJobDataMap().put("name", "quartz-reconciliations");
            //			jobDetail.getJobDataMap().put("executorNo", task.getExecutorNo());
            //			jobDetail.getJobDataMap().put("sendType", task.getSendType());
            //			jobDetail.getJobDataMap().put("url", task.getUrl());
            //			jobDetail.getJobDataMap().put("executeParamter", task.getExecuteParamter());
            scheduler.scheduleJob(jobDetail, trigger);
            logger.info("task 'quartz-reconciliations' schedulerRule :'*/10 * * * * ?' reload succeed");
        }
        catch (Exception e) {
            logger.info("定时任务加载失败，请手动加载！\n");
            logger.info("定时任务加载异常:", e);
        }
        logger.info("定时任务加载完成");
    }

}


